<template>
  <div>
    <div>精灵模型Sprite</div>
    <div ref="webgl"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  let scene: any = null;
  let camera: any = null;
  let render: any = null;
  let controls: OrbitControls;
  onMounted(() => {
    init();
  });
  function init() {
    scene = new THREE.Scene();

    const width = 600; //canvas画布宽度
    const height = 600; //canvas画布高度

    camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
    camera.position.set(300, 300, 300);
    camera.lookAt(scene.position);
    render = new THREE.WebGLRenderer();
    // 背景颜色
    render.setClearColor('#f1f2f6');
    render.setSize(width, height);
    // 设置渲染器，允许光源阴影渲染
    render.shadowMap.enabled = true;
    render.shadowMap.type = THREE.PCFSoftShadowMap;

    webgl.value.appendChild(render.domElement);
    controls = new OrbitControls(camera, render.domElement);
    // const amLight = new THREE.AmbientLight(0xffffff);
    // scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);
    // 创建精灵材质对象SpriteMaterial
    const spriteMaterial = new THREE.SpriteMaterial({
      color: 0x00ffff, //设置颜色
      rotation: Math.PI / 4,
    });

    // 创建精灵模型对象，不需要几何体geometry参数
    const sprite = new THREE.Sprite(spriteMaterial);
    sprite.scale.set(20, 20, 1);
    sprite.position.set(30, 0, 0);
    scene.add(sprite);
    renderFun();
  }

  function renderFun() {
    controls.update();
    // controls.update(); //update()函数内会执行camera.lookAt(controls.target)
    render.render(scene, camera);
    requestAnimationFrame(renderFun);
  }
</script>
<style lang=""></style>
